package com.hvgroup.modules.sanic.service.impl;

import com.hvgroup.modules.sanic.service.SeleniumService;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于执行 Bing 搜索 并抓取结果页内容，解决 LLM 问答中“从网页补充信息”的需求。
 */

@Slf4j
@Service
@RequiredArgsConstructor
public class SeleniumServiceImpl implements SeleniumService {

//    @Value("${chrome.driver.path}")
    private String chromeDriverPath;

    @Override
    public String getBingFirstHref(String keyword) {
        try {
            String url = "https://www.bing.com/search?q=" + keyword + "&mkt=zh-CN";
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3")
                    .get();

            Element cite = doc.selectFirst("div.b_attribution cite");
            return cite != null ? cite.text().trim() : null;
        } catch (Exception e) {
            log.error("请求Bing失败: {}", e.getMessage(), e);
            return null;
        }
    }

    @Override
    public String getSearchResultsLinks(String query) {
        System.setProperty("webdriver.chrome.driver", chromeDriverPath);
        WebDriver driver = initDriver();
        try {
            driver.get("https://www.bing.com/?mkt=zh-CN");
            WebElement searchBox = driver.findElement(By.name("q"));
            searchBox.sendKeys(query);
            searchBox.submit();

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            List<WebElement> elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//li[@class='b_algo']/h2/a")));

            List<String> links = new ArrayList<>();
            int numLinks = 1;
            for (int i = 2; i < Math.min(elements.size(), 2 + numLinks); i++) {
                links.add(elements.get(i).getAttribute("href"));
            }

            StringBuilder content = new StringBuilder();
            for (String link : links) {
                content.append("\n----------------------------------------\n")
                        .append(fetchPageText(link));
            }
            return content.toString();
        } catch (Exception e) {
            log.error("搜索失败: {}", e.getMessage(), e);
            return null;
        } finally {
            driver.quit();
        }
    }

    private String fetchPageText(String url) {
        WebDriver driver = initDriver();
        try {
            driver.get(url);
            String html = driver.getPageSource();
            Document doc = Jsoup.parse(html);
            doc.body();
            return doc.body().text();
        } finally {
            driver.quit();
        }
    }

    private WebDriver initDriver() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless", "--disable-gpu", "start-maximized", "--disable-extensions");
        return new ChromeDriver(options);
    }
}
